const express = require("express");
const multer = require("multer"); // 上传插件
const { UPLOAD_PATH } = require("../utils/constant");
const Result = require("../models/Result");
const router = express.Router();
const Book = require("../models/Book");
const boom = require("boom");
const { decode } = require("../utils/index");
const bookService = require("../service/book");

router.post(
  "/upload", // uri
  multer({ dest: `${UPLOAD_PATH}/book` }).single("file"), // single 表示上传单个文件
  function (req, res, next) {
    if (!req.file || req.file.length === 0) {
      new Result("上传电子书失败").fail(res);
    } else {
      const book = new Book(req.file);
      // 调用book parse方法, 返回promise对象, 链式调用
      book
        .parse()
        .then((book) => {
          new Result(book, "上传电子书成功").success(res); // 返回解析后的book
        })
        .catch((err) => {
          next(boom.badImplementation(err)); // 返回1个 500 错误
        });
    }
  }
);
// 保存图书信息
router.post("/create", function (req, res, next) {
  //从req获取用户名
  const decoded = decode(req);
  // 添加进 username信息
  if (decoded && decoded.username) {
    req.body.username = decoded.username;
  }
  const book = new Book(null, req.body); //body 即为 上传的 data
  // console.log("create book from data:",book);
  bookService
    .insertBook(book)
    .then(() => {
      new Result("添加电子书成功").success(res);
    })
    .catch((err) => {
      next(boom.badImplementation(err));
    });
});

router.get("/get", function (req, res, next) {
  const { fileName } = req.query;
  if (!fileName) {
    next(boom.badRequest(new Error("参数fileName不能为空"))); // badReq 是400错误，缺少参数
  } else {
    bookService
      .getBook(fileName)
      .then((data) => {
        new Result(data, "获取图书信息成功").success(res);
      })
      .catch((err) => {
        next(boom.badImplementation(err)); // 代码错误
      });
  }
});
// update 图书信息
router.post("/update", function (req, res, next) {
  //从req获取用户名
  const decoded = decode(req);
  // 添加进 username信息
  if (decoded && decoded.username) {
    req.body.username = decoded.username;
  }
  const book = new Book(null, req.body); //body 即为 上传的 data
  // console.log("create book from data:",book);
  bookService
    .updateBook(book)
    .then(() => {
      new Result("更新电子书成功").success(res);
    })
    .catch((err) => {
      next(boom.badImplementation(err));
    });
});

router.get("/category", function (req, res, next) {
  bookService
    .getCategory()
    .then((result) => {
      new Result(result, "获取分类成功").success(res);
    })
    .catch((err) => {
      next(boom.badImplementation(err));
    });
});

router.get("/list", function (req, res, next) {
  bookService
    .listBook(req.query)
    .then(({ list }) => {
      new Result({ list }, "获取图书列表成功").success(res);
    })
    .catch((err) => {
      next(boom.badImplementation(err));
    });
});

module.exports = router;
